//
//  DataBase.m
//  rss_reader
//
//  Created by Oleg Soldatoff on 4/13/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DataBase.h"


@implementation DataBase


- (void) configBase {

  if (sqlite3_threadsafe() > 0) {
    int retCode = sqlite3_config(SQLITE_CONFIG_SERIALIZED);
    if (retCode == SQLITE_OK) {
      NSLog(@"Can now use sqlite on multiple threads, using the same connection");
    } else {
      NSLog(@"setting sqlite thread safe mode to serialized failed!!! return code: %d", retCode);
    }
  } else {
    NSLog(@"Your SQLite database is not compiled to be threadsafe.");
  }



}

- (NSString *) databasePath {

  // Get the documents directory
  NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *docsDir = [dirPaths objectAtIndex:0];
  //NSLog(@"HOME - %@", docsDir);
  // Build the path to the database file
  return [[[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"feeds.db"]]autorelease];

}

- (id)init
{
   NSLog(@"NEW CLASSSSSS");
  self = [super init];
  if (self) {
    
    [self configBase];
    sqlite3 *feedsDB;
    NSFileManager *filemgr = [NSFileManager defaultManager];
    if ([filemgr fileExistsAtPath: [self databasePath]] == NO)
    {
      const char *dbpath = [[self databasePath] UTF8String];
      [self configBase];

      if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
      {
        NSLog(@"NEW CLASSSSSS");
        char *errMsg;
        //Sites ( ID , URL, NAME)
        //Feeds (ID, SITE_ID, URL, NAME, STATUS)
        //Articles(ID, FEED_ID, URL, NAME, DESC, DATE, STATUS)
        const char *sql_stmt = "CREATE TABLE IF NOT EXISTS SITES (ID INTEGER PRIMARY KEY AUTOINCREMENT, URL TEXT, NAME TEXT);CREATE TABLE IF NOT EXISTS FEEDS (ID INTEGER PRIMARY KEY AUTOINCREMENT, SITE_ID INTEGER, URL TEXT, NAME TEXT, STATUS INTEGER); CREATE TABLE IF NOT EXISTS ARTICLES (ID INTEGER PRIMARY KEY AUTOINCREMENT, FEED_ID INTEGER, URL TEXT, NAME TEXT, DESC TEXT, DATE TEXT, STATUS INTEGER)";
        
        if (sqlite3_exec(feedsDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
        {
          NSLog(@"Failed to create table");
        }
       sqlite3_close(feedsDB); 
      } else {
        NSLog(@"Failed to open/create database");
      }
    }
    /*[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(pocessNotification:)  
                                                 name:@"xmlRecieved" 
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(pocessNotification:)  
                                                 name:@"ErrorInNetwork" 
                                               object:nil]; 
*/
  }
  exampleQueue = dispatch_queue_create( "com.example.update.news", NULL );

  return self;
}

- (void) dealloc {

  [[NSNotificationCenter defaultCenter] removeObserver:self]; 
   dispatch_release( exampleQueue );
  [super dealloc];
  
}


- (NSMutableArray *) baseSites
{
  
 
    sqlite3 *feedsDB;
    NSMutableArray *baseSites = [[[NSMutableArray alloc]init]autorelease];
    const char *dbpath = [[self databasePath] UTF8String];
    sqlite3_stmt    *statement;
  [self configBase];

    if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
    {
      NSString *querySQL = [NSString stringWithString: @"SELECT * FROM SITES"];
      const char *query_stmt = [querySQL UTF8String];
      if (sqlite3_prepare_v2(feedsDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
      {
        while(sqlite3_step(statement) == SQLITE_ROW)
        {
          //Sites ( ID , URL, NAME)
          NSNumber *siteID = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
          NSString *siteURL = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)]autorelease];
          NSString *siteName = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]autorelease];
          NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                                            siteID,   @"ID", 
                                            siteURL,  @"URL", 
                                            siteName, @"NAME", nil];
          
          [baseSites addObject:dic];        
          } 
        sqlite3_finalize(statement);
      }
    }
  sqlite3_close(feedsDB);
  return baseSites;
}

-(NSMutableArray *) baseAllFeeds {

  NSString *querySQL;
    sqlite3 *feedsDB;
  
    
    NSMutableArray *baseAllFeeds = [[[NSMutableArray alloc]init]autorelease];
    const char *dbpath = [[self databasePath] UTF8String];
    sqlite3_stmt    *statement;
  [self configBase];

    if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
    {
      querySQL = [NSString stringWithFormat:@"SELECT * FROM FEEDS"];
      
      const char *query_stmt = [querySQL UTF8String];
      
      if (sqlite3_prepare_v2(feedsDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
      {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
          //Feeds (ID, SITE_ID, URL, NAME, STATUS)
          NSNumber *feedID = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
          NSNumber *siteID = [NSNumber numberWithInt: sqlite3_column_int(statement, 1)];
          NSString *feedURL = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]autorelease];
          NSString *feedName = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)]autorelease];
          NSNumber *feedSTATUS = [NSNumber numberWithInt: sqlite3_column_int(statement, 4)];
          
          NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                               feedID,     @"ID", 
                               siteID,     @"SITE_ID", 
                               feedURL,    @"URL", 
                               feedName,   @"NAME", 
                               feedSTATUS, @"STATUS", nil];
          
          [baseAllFeeds addObject:dic];        
        } 
        sqlite3_finalize(statement);
      }
      sqlite3_close(feedsDB);
    }
 
  
  return baseAllFeeds;

}




- (NSNumber *) saveSite: (NSString*) siteName {
  
  sqlite3_stmt    *statement;
  NSNumber        *siteID;
  NSString        *siteLabel;
    sqlite3 *feedsDB;
  
  if ( [siteName hasPrefix:@"http://"] == YES ) {
    NSRange range = NSMakeRange (7, [siteName length]-7);
       siteLabel = [NSString stringWithFormat:@"%@", [siteName substringWithRange:range]];
    
  }
  
  const char *dbpath = [[self databasePath] UTF8String];
  [self configBase];

  if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
  {

    // NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO SITES (URL, NAME) SELECT '%@', '%@' WHERE NOT EXISTS (SELECT 1 FROM SITES WHERE URL LIKE '%@');",siteName,siteLabel,siteName];
    
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO SITES (URL, NAME) SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM SITES WHERE URL LIKE ?);"];
      
   const char *insert_stmt = [insertSQL UTF8String];
      
   sqlite3_prepare_v2(feedsDB, insert_stmt, -1, &statement, NULL);
    
   sqlite3_bind_text(statement, 1, [siteName UTF8String],   -1, SQLITE_TRANSIENT);
   sqlite3_bind_text(statement, 2, [siteLabel UTF8String],  -1, SQLITE_TRANSIENT);
   sqlite3_bind_text(statement, 3, [siteName UTF8String],   -1, SQLITE_TRANSIENT);

    
    
   if (sqlite3_step(statement) == SQLITE_DONE)
      {
        NSLog(@"Site added");
        sqlite3_finalize(statement);
        
        NSString *querySQL = [NSString stringWithFormat:@"SELECT * FROM SITES WHERE URL LIKE '%@'", siteName];
        
        const char *query_stmt = [querySQL UTF8String];
        
        if (sqlite3_prepare_v2(feedsDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
          if (sqlite3_step(statement) == SQLITE_ROW)
          {
            siteID = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
          }
        }
        
      } else {
        NSLog(@"Failed to add site");
      }
      sqlite3_finalize(statement);
  }
    
  sqlite3_close(feedsDB);
  return siteID;
}

- (BOOL) sqliteDo: (NSString *) sqlQuery, ... {

  BOOL result;
  int param_count;
  sqlite3_stmt    *statement;
  sqlite3 *feedsDB;
  
  const char *dbpath = [[self databasePath] UTF8String];
  [self configBase];

  if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
  {
    const char *query_stmt = [sqlQuery UTF8String];
    sqlite3_prepare_v2(feedsDB, query_stmt, -1, &statement, NULL);
    
    va_list args;
    va_start(args, sqlQuery);
    
    if ((param_count = sqlite3_bind_parameter_count(statement))) {
      for (int i = 0; i < param_count; i++) {
        id o = va_arg(args, id);
        
        // determine the type of the argument
        if (o == nil) {
          sqlite3_bind_null(statement, i + 1);
        } else if ([o respondsToSelector:@selector(objCType)]) {
          if (strchr("islISLB", *[o objCType])) { // integer
            sqlite3_bind_int(statement, i + 1, [o intValue]);
          } else if (strchr("fd", *[o objCType])) {   // double
            sqlite3_bind_double(statement, i + 1, [o doubleValue]);
          } else {    // unhandled types
            NSLog(@"bindSQL: Unhandled objCType: %s", [o objCType]);
            statement = NULL;
            return NO;
          }
        } else if ([o respondsToSelector:@selector(UTF8String)]) { // string
          sqlite3_bind_text(statement, i + 1, [o UTF8String], -1, SQLITE_TRANSIENT);
        } else {    // unhhandled type
          NSLog(@"bindSQL: Unhandled parameter type: %@", [o class]);
          statement = NULL;
          return NO;
        }
      }
    }
    
    va_end(args);
    
    if (sqlite3_step(statement) == SQLITE_DONE)
    {
      //NSLog(@"DB updated");
      result = YES;
    } else {
      NSLog(@"Failed to update DB");
      NSLog(@"%@", sqlQuery);
      result = NO;
    }
    sqlite3_finalize(statement);
  }
  sqlite3_close(feedsDB);
  
  return result;
}


- (void) saveFeeds: (NSArray*) feedsArr forSite: (NSNumber*) siteID {
  
     //title , href
    //Feeds (ID, SITE_ID, URL, NAME, STATUS)
    
  
  NSMutableString *stringWithSelectedFeedsURLs = [[[NSMutableString alloc]init]autorelease];
  
  for (NSDictionary *dicFeedsOfSite in feedsArr) { 
    
    if ( [feedsArr lastObject] == dicFeedsOfSite )
            [stringWithSelectedFeedsURLs appendFormat:@"'%@'", [dicFeedsOfSite valueForKey: @"href"]];
    else    [stringWithSelectedFeedsURLs appendFormat:@"'%@', ", [dicFeedsOfSite valueForKey: @"href"]];
    
  }

  //Delete articles
  NSString *deleteArticles = [NSString stringWithFormat:@"DELETE FROM ARTICLES WHERE FEED_ID IN (SELECT ID FROM FEEDS WHERE SITE_ID = %@ AND URL NOT IN (%@));", siteID, stringWithSelectedFeedsURLs];
  
  [self sqliteDo:deleteArticles];
  //NSLog(@"DELEET ARTICLES - %@",deleteArticles );
    
  //Delete feeds that were unchecked
  NSString *deleteFeeds = [NSMutableString stringWithFormat:@"DELETE FROM FEEDS WHERE SITE_ID = %@ AND URL NOT IN (%@);", siteID, stringWithSelectedFeedsURLs];
  //NSLog(@"dleter - %@", deleteFeeds);
  [self sqliteDo:deleteFeeds];
    
  //Add new feeds if they not in DB    
  for (NSDictionary *dicFeedsOfSite in feedsArr) {
      
    NSString *insertFeed = [NSString stringWithFormat:@"INSERT INTO FEEDS (SITE_ID, URL, NAME, STATUS) SELECT ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM FEEDS WHERE URL LIKE ? );"];
    [self sqliteDo:insertFeed,
                       siteID,
                       [dicFeedsOfSite valueForKey: @"href"],
                       [dicFeedsOfSite valueForKey: @"title"],
                       [NSNumber numberWithInt: 0], 
                       [dicFeedsOfSite valueForKey: @"href"]];
   }
   
}

- (void) deleteSite: (NSString*) siteURL {

  NSString *deleteSite = [NSString stringWithFormat:@"DELETE FROM SITES WHERE URL LIKE '%@'", siteURL];
  [self sqliteDo:deleteSite];
  
}

- (void) addFeeds: (NSMutableArray*) arrWithFeeds forSite: (NSString*) siteName {
  
  [self saveFeeds: arrWithFeeds forSite:[self saveSite:siteName]];
   
  if ([arrWithFeeds count] == 0) {
    [self deleteSite:siteName];
  }
 

}



- (void) saveArticles: (NSArray*) articlesArr forFeed: (NSNumber*) feedID {
           
  
  NSMutableString *stringWithURLsOfArticles = [[[NSMutableString alloc]init]autorelease];
  
  for (NSDictionary *dicArticle in articlesArr) { 
    
    if ( [articlesArr lastObject] == dicArticle )
            [stringWithURLsOfArticles appendFormat:@"'%@'",   [dicArticle valueForKey: @"link"]];
    else    [stringWithURLsOfArticles appendFormat:@"'%@', ", [dicArticle valueForKey: @"link"]];
    
  }
  
  //Delete articles
  NSString *deleteArticles = [NSString stringWithFormat:@"DELETE FROM ARTICLES WHERE STATUS !=1 AND FEED_ID = %@ AND URL NOT IN (%@);", feedID, stringWithURLsOfArticles];

  //NSLog(@"DELEET ARTICLES - %@",deleteArticles );
  [self sqliteDo:deleteArticles];
  
  //Add articles
  for (NSDictionary *dicArticleOfFeed in articlesArr) {
  
      NSString *insertArticle = [NSString stringWithFormat:@"INSERT INTO ARTICLES (FEED_ID, URL, NAME, DESC, DATE, STATUS) SELECT ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM ARTICLES WHERE URL LIKE ? AND  FEED_ID = ?);"];
      //NSLog(@"%@", insertArticle);
      [self sqliteDo:insertArticle, 
                      feedID, 
                      [dicArticleOfFeed valueForKey: @"link"],       
                      [dicArticleOfFeed valueForKey: @"title"],
                      [dicArticleOfFeed valueForKey: @"description"],
                      [dicArticleOfFeed valueForKey: @"pubdate"],
                      [NSNumber numberWithInt: 0], 
                      [dicArticleOfFeed valueForKey: @"link"],
                      feedID];
  }
}


- (NSNumber *) siteIDForSite: (NSString*) siteName {

  for (NSDictionary *dicSite in self.baseSites) {
    if ([[dicSite valueForKey:@"URL"] isEqualToString: siteName] == YES ) {
      return [dicSite valueForKey:@"ID"];
    }
  }
  return [NSNumber numberWithInt:0];

}

- (NSNumber *) feedIDFromFeedURL: (NSString*) feedURL {
  
  sqlite3 *feedsDB;
  NSNumber *result;
  const char *dbpath = [[self databasePath] UTF8String];
  sqlite3_stmt    *statement;
  [self configBase];

  if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
    {
      NSString *querySQL = [NSString stringWithFormat:@"SELECT ID FROM FEEDS WHERE URL LIKE '%@'", feedURL];
      const char *query_stmt = [querySQL UTF8String];
      if (sqlite3_prepare_v2(feedsDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
      {
        if (sqlite3_step(statement) == SQLITE_ROW)
        {
          result = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
          NSLog(@"FEED ID FROM FEED URL!!!");
        } 
        sqlite3_finalize(statement);
      }
      else {
        NSLog(@"PROBLEMS IN FEED ID FROM FEED URL!!!");
      }
     
    }
   sqlite3_close(feedsDB);
   return result;
  
}

- (void) articleDidReadWihStatus: (NSString*) articleURL {
  
  NSString *articleDidReadQuery = [NSString stringWithFormat:@"UPDATE ARTICLES SET STATUS = -1 WHERE URL LIKE '%@';", articleURL];
  [self sqliteDo:articleDidReadQuery];
  //[[NSNotificationCenter defaultCenter] postNotificationName:@"BaseUpdated" object:self];
  
}

- (void) articleDidRead: (NSString*) articleURL {
    
  NSString *articleDidReadQuery = [NSString stringWithFormat:@"UPDATE ARTICLES SET STATUS = -1 WHERE URL LIKE '%@' AND STATUS != 1;", articleURL];
  [self sqliteDo:articleDidReadQuery];
  //[[NSNotificationCenter defaultCenter] postNotificationName:@"BaseUpdated" object:self];
  
}

- (void) articleWillRead: (NSString*) articleURL{

  NSString *articleDidReadQuery = [NSString stringWithFormat:@"UPDATE ARTICLES SET STATUS = 1 WHERE URL LIKE '%@';", articleURL];
  [self sqliteDo:articleDidReadQuery];
  [[NSNotificationCenter defaultCenter] postNotificationName:@"BaseUpdated" object:self];

}

- (NSNumber *) newArticles {
    NSNumber        *result;
    sqlite3_stmt    *statement;
    sqlite3 *feedsDB;
    const char      *dbpath = [[self databasePath] UTF8String];
  [self configBase];

    if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)  {
      NSString *countSQL = [NSString stringWithFormat:@"SELECT COUNT (DISTINCT URL) FROM ARTICLES WHERE STATUS = 0;"];
      const char *count_stmt = [countSQL UTF8String];

      if (sqlite3_prepare_v2(feedsDB, count_stmt, -1, &statement, NULL) == SQLITE_OK) {

        if (sqlite3_step(statement) == SQLITE_ROW) {
            result = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
        }
      }
    }   
    sqlite3_finalize(statement);
    sqlite3_close(feedsDB);
    return result;
}

- (NSNumber *) newArticlesForSiteID: (NSNumber *) siteID {
  NSNumber        *result;
  result = 0;
  sqlite3_stmt    *statement;
  sqlite3 *feedsDB;
  const char      *dbpath = [[self databasePath] UTF8String];
  [self configBase];

  if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)  {
    NSString *countSQL = [NSString stringWithFormat:@"SELECT COUNT (DISTINCT URL) FROM ARTICLES  WHERE STATUS =0 AND  FEED_ID IN (select id from feeds where site_id = %@)", siteID];
    const char *count_stmt = [countSQL UTF8String];
    if (sqlite3_prepare_v2(feedsDB, count_stmt, -1, &statement, NULL) == SQLITE_OK) {
      
      if (sqlite3_step(statement) == SQLITE_ROW) {
        result = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
      }
    }
  }   
  sqlite3_finalize(statement);
  sqlite3_close(feedsDB);
  return result;
}
//geeeee

- (NSNumber *) newArticlesForFeedID: (NSNumber *) feedID {
  NSNumber        *result;
  result = 0;
  sqlite3_stmt    *statement;
  sqlite3 *feedsDB;
  const char      *dbpath = [[self databasePath] UTF8String];
  [self configBase];

  if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)  {
    NSString *countSQL = [NSString stringWithFormat:@"SELECT COUNT (DISTINCT URL) FROM ARTICLES  WHERE STATUS =0 AND  FEED_ID = %@", feedID];
    const char *count_stmt = [countSQL UTF8String];
    if (sqlite3_prepare_v2(feedsDB, count_stmt, -1, &statement, NULL) == SQLITE_OK) {
      
      if (sqlite3_step(statement) == SQLITE_ROW) {
        result = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
      }
    }
  }   
  sqlite3_finalize(statement);
  sqlite3_close(feedsDB);
  return result;
}



-(void) updateAllFromInet {
  
 
  [[Updater sharedUpdater] updateAllFromInet];
  
  /*
   
  NSMutableArray *tmpFeeds = [self baseFeedsForSiteID: 0];
  [tmpFeeds retain];
  
  dispatch_async( exampleQueue, ^{
    UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = YES;
    NSLog(@"Dispatch async started");
    
       
    for (NSDictionary *feedDic in tmpFeeds) {
      [self startTheBackgroundJob: feedDic];
    }
    NSLog(@"For ended");
   
    dispatch_sync( dispatch_get_main_queue(), ^{
 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"BaseUpdated" object:self];
      app.networkActivityIndicatorVisible = NO;
      NSLog(@"ReloadTable");
    });
  });
  [tmpFeeds release];
  */
}



- (void)startTheBackgroundJob: (NSDictionary *) feedDic  {  
  
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
  NSLog(@"startTheBackgroundJob feed URL - %@", feedDic);
  [[[[Network alloc]init]autorelease]giveXML:feedDic];
  
  //[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
  while ([runLoop runMode:NSDefaultRunLoopMode
               beforeDate:[NSDate distantFuture]]);
  [pool release]; 
  NSLog(@"Thread stopped");
}  

- (void) pocessNotification:(NSNotification *) notification { 

    if ( [[notification name] isEqualToString:@"xmlRecieved"] )   { 
      
      NSLog(@"%@", [[notification userInfo] valueForKey:@"ID"]);
      
      Network * netw = [notification object];
      
      [self saveArticles: [XMLParser arrayWithItems:[netw receivedData]]
                    forFeed: [[notification userInfo] valueForKey:@"ID"]];
      
    } else if ( [[notification name] isEqualToString:@"ErrorInNetwork"] ) {

      [[[[UIAlertView alloc]initWithTitle:@"Network error"
                                 message:[NSString stringWithFormat:@"Problems while connecting to %@", [[notification userInfo] valueForKey:@"URL"] ] 
                                delegate:nil 
                       cancelButtonTitle:@"Ok" 
                       otherButtonTitles: nil]autorelease]show];
    
    }

      
}  



- (NSMutableArray *)baseNews: (NSInteger) view forFeedID: (NSInteger) feedID {

    
  NSMutableArray * baseNews = [[[NSMutableArray alloc]init]autorelease];
  NSMutableString *querySQL;
  sqlite3 *feedsDB;
 // @"All", @"New", @"To read",
  switch (view) {
    case 0://All
      if ( feedID != 0 ) 
        querySQL = [NSMutableString stringWithFormat:@"SELECT URL,ID,FEED_ID,NAME,DESC,DATE,STATUS FROM ARTICLES WHERE FEED_ID = %d ORDER BY STATUS DESC, DATE DESC", feedID];
      else 
        querySQL = [NSMutableString stringWithFormat:@"SELECT URL, ID, FEED_ID, NAME, DESC, DATE, STATUS FROM ARTICLES GROUP BY URL ORDER BY DATE DESC"];
      break;
    case 2:
      if ( feedID != 0 ) 
        querySQL = [NSMutableString stringWithFormat:@"SELECT URL,ID,FEED_ID,NAME,DESC,DATE,STATUS FROM ARTICLES WHERE FEED_ID = %d AND STATUS = 1 ORDER BY STATUS DESC, DATE DESC", feedID];
      else 
        querySQL = [NSMutableString stringWithFormat:@"SELECT URL, ID, FEED_ID, NAME, DESC, DATE, STATUS FROM ARTICLES WHERE STATUS = 1 GROUP BY URL ORDER BY DATE DESC"];
      break;  
    default:
      if ( feedID != 0 ) 
        querySQL = [NSMutableString stringWithFormat:@"SELECT URL,ID,FEED_ID,NAME,DESC,DATE,STATUS FROM ARTICLES WHERE FEED_ID = %d AND STATUS = 0 ORDER BY STATUS DESC, DATE DESC", feedID];
      else 
        querySQL = [NSMutableString stringWithFormat:@"SELECT URL, ID, FEED_ID, NAME, DESC, DATE, STATUS FROM ARTICLES WHERE STATUS = 0 GROUP BY URL ORDER BY DATE DESC"];
      break;
  }
  NSLog(@"%@", querySQL);
  
  const char *dbpath = [[self databasePath] UTF8String];
  sqlite3_stmt    *statement;
  [self configBase];

    if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
    {
      
      const char *query_stmt = [querySQL UTF8String];
      
      if (sqlite3_prepare_v2(feedsDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
      {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
          //Articles(ID, FEED_ID, URL, NAME, DESC, DATE, STATUS)
          NSString *articleURL = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]autorelease];
          NSNumber *articleID = [NSNumber numberWithInt: sqlite3_column_int(statement, 1)];
          NSNumber *feedID = [NSNumber numberWithInt: sqlite3_column_int(statement, 2)];
          
          NSString *articleName = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)]autorelease];
          NSString *articleDesc = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 4)]autorelease];
          NSString *articleDate = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 5)]autorelease];
          NSNumber *articleStatus = [NSNumber numberWithInt: sqlite3_column_int(statement, 6)];
          
          NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                               articleID,     @"ID", 
                               feedID,        @"FEED_ID", 
                               articleURL,    @"URL", 
                               articleName,   @"NAME", 
                               articleDesc,   @"DESC",
                               articleDate,   @"DATE",
                               articleStatus, @"STATUS", nil];
          
          [baseNews addObject:dic];        
        } 
        sqlite3_finalize(statement);
      }
    }
    sqlite3_close(feedsDB);
  
  return baseNews;
  
}



- (NSMutableArray *) baseFeedsForSiteID:(NSInteger) siteID {

  NSString *querySQL;
  sqlite3 *feedsDB;
  NSMutableArray *baseFeeds; 
    
    baseFeeds = [[[NSMutableArray alloc]init]autorelease];
    const char *dbpath = [[self databasePath] UTF8String];
    sqlite3_stmt    *statement;
  [self configBase];

    if (sqlite3_open(dbpath, &feedsDB) == SQLITE_OK)
    {
      if ( 0 != siteID ) querySQL = [NSString stringWithFormat:@"SELECT * FROM FEEDS WHERE SITE_ID = %d", siteID];
      else querySQL = [NSString stringWithFormat:@"SELECT * FROM FEEDS"];
      
      const char *query_stmt = [querySQL UTF8String];
      
      if (sqlite3_prepare_v2(feedsDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
      {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
          //Feeds (ID, SITE_ID, URL, NAME, STATUS)
          NSNumber *feedID = [NSNumber numberWithInt: sqlite3_column_int(statement, 0)];
          NSNumber *siteID = [NSNumber numberWithInt: sqlite3_column_int(statement, 1)];
          NSString *feedURL = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]autorelease];
          NSString *feedName = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)]autorelease];
          NSNumber *feedSTATUS = [NSNumber numberWithInt: sqlite3_column_int(statement, 4)];
          
          NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                               feedID,     @"ID", 
                               siteID,     @"SITE_ID", 
                               feedURL,    @"URL", 
                               feedName,   @"NAME", 
                               feedSTATUS, @"STATUS", nil];
          
          [baseFeeds addObject:dic];        
        } 
        sqlite3_finalize(statement);
      }
      sqlite3_close(feedsDB);
    }
 
  return baseFeeds;

  

}

@end